package com.ruoyi.web.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.AiRequire;
import com.ruoyi.system.domain.AiRequirePlan;
import com.ruoyi.system.domain.AiUserRequireRelation;
import com.ruoyi.system.domain.vo.AiRequireScopeTypeReqVo;
import com.ruoyi.system.domain.vo.AiRequireVo;
import com.ruoyi.system.domain.vo.AiUserRequireReqVo;
import com.ruoyi.system.domain.vo.SysUserVo;
import com.ruoyi.system.service.IAiRequirePlanService;
import com.ruoyi.system.service.IAiRequireService;
import com.ruoyi.system.service.IAiUserRequireRelationService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户商机信息-对外API接口请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/require")
public class ApiAiRequireController extends BaseController {

    @Autowired
    private IAiRequireService requireService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IAiUserRequireRelationService userRequireRelationService;
    @Autowired
    private IAiRequirePlanService requirePlanService;

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "根据商机ID获取商机信息详情")
    public AjaxResult getById(@PathVariable("id") Long id) {
        AiRequire require = requireService.selectAiRequireById(id);
        if (null == require) return AjaxResult.success();
        AiRequireVo resp = new AiRequireVo();
        BeanUtil.copyProperties(require, resp);
        SysUser sysUser = sysUserService.selectUserById(require.getUserId());
        if (null != sysUser) {
            resp.setUser(new SysUserVo(sysUser.getUserId(), sysUser.getNickName(), sysUser.getAvatar()));
        }
        return AjaxResult.success(resp);
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "根据sessionId, topicId, schemeId条件，获取商机信息列表(带分页参数)")
    public AjaxResult list(@RequestParam(value = "sessionId", required = false) String sessionId,
                           @RequestParam(value = "topicId", required = false) String topicId,
                           @RequestParam(value = "schemeId", required = false) Long schemeId,
                           @RequestParam(value = "current", required = false) Long current,
                           @RequestParam(value = "size", required = false) Long size) {
        AiRequire require = new AiRequire();
        require.setSessionId(sessionId);
        require.setTopicId(topicId);
        require.setSchemeId(schemeId);
        require.setStatus("0");  // 查找正常状态的商机列表
        require.setScopeType("0"); // 查找公开范围的商机列表
        require.setInitFlag("1"); // 查询之前商机，非讨论商机
        Map<String, Object> params = new HashMap<>();
        params.put("page", SqlUtil.getLimit(current, size));
        require.setParams(params);
        List<AiRequire> requireList = requireService.selectAiRequireList(require);
        if (CollUtil.isEmpty(requireList)) return AjaxResult.success(new ArrayList<>());
        return AjaxResult.success(requireList.stream().map(this::changeItem).collect(Collectors.toList()));
    }

    @GetMapping(value = "/list/mine")
    @ApiOperation(value = "获取当前用户的商机信息列表(带分页参数)")
    public AjaxResult listMine(@RequestParam(value = "current", required = false) Long current,
                               @RequestParam(value = "size", required = false) Long size) {
        AiRequire require = new AiRequire();
        require.setUserId(getUserId());
        require.setStatus("0"); // 查找正常状态的商机列表
        require.setInitFlag("1"); // 查询之前商机，非讨论商机
        Map<String, Object> params = new HashMap<>();
        params.put("page", SqlUtil.getLimit(current, size));
        require.setParams(params);
        List<AiRequire> requireList = requireService.selectAiRequireList(require);
        if (CollUtil.isEmpty(requireList)) return AjaxResult.success(new ArrayList<>());
        return AjaxResult.success(requireList.stream().map(this::changeItem).collect(Collectors.toList()));
    }

    @GetMapping(value = "/list/discuss")
    @ApiOperation(value = "获取商机讨论信息列表(带分页参数)")
    public AjaxResult listDiscuss(@RequestParam(value = "current", required = false) Long current,
                                  @RequestParam(value = "size", required = false) Long size) {
        AiRequire require = new AiRequire();
        // require.setUserId(getUserId());
        require.setInitFlag("2"); // 讨论商机
        require.setStatus("0"); // 查找正常状态的商机列表
        Map<String, Object> params = new HashMap<>();
        params.put("page", SqlUtil.getLimit(current, size));
        require.setParams(params);
        List<AiRequire> requireList = requireService.selectAiRequireList(require);
        if (CollUtil.isEmpty(requireList)) return AjaxResult.success(new ArrayList<>());
        return AjaxResult.success(requireList.stream().map(this::changeItem).collect(Collectors.toList()));
    }

    @Log(title = "【用户商机讨论】", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add/discuss/{openId}")
    @ApiOperation(value = "新增用户商机讨论信息")
    public AjaxResult add(@PathVariable("openId") String openId,  @RequestBody AiRequire require) {
        if (null == require) return AjaxResult.error("请求参数不能为空");
        if (StrUtil.isBlank(require.getContent())) return AjaxResult.error("请求参数内容不能为空");
        SysUser sysUser = sysUserService.selectUserByUserName(openId);
        if (null == sysUser) return AjaxResult.error("用户不存在");
        require.setUserId(sysUser.getUserId());
        require.setSchemeId(0L);  // 需求讨论不关联方案
        require.setInitFlag("2"); // 需求讨论，通过initFlag=2进行区分
        return AjaxResult.success(requireService.insertAiRequire(require));
    }

    @Log(title = "【用户商机】", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增用户商机信息")
    public AjaxResult add(@RequestBody List<AiRequire> requires) {
        if (CollUtil.isEmpty(requires)) return AjaxResult.error("请求参数为空");
        for (AiRequire require : requires) {
            require.setUserId(getUserId());
            requireService.insertAiRequire(require);
        }
        return AjaxResult.success(1);
    }

    @Log(title = "【用户商机】", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/scope")
    @ApiOperation(value = "修改用户商机范围查看类型")
    public AjaxResult updateScope(@RequestBody AiRequireScopeTypeReqVo req) {
        if (null == req) return AjaxResult.error("请求参数为空");
        AiRequire require = requireService.selectAiRequireById(req.getId());
        if (null == require || !require.getUserId().equals(SecurityUtils.getUserId()))
            return AjaxResult.error("用户商机不存在");
        AiRequire aiRequire = new AiRequire();
        aiRequire.setId(req.getId());
        aiRequire.setScopeType(req.getScopeType());
        return AjaxResult.success(requireService.updateAiRequire(aiRequire));
    }

    @Transactional
    @PostMapping(value = "/relation/add")
    @ApiOperation(value = "新增用户商机关联关系信息")
    public AjaxResult addRelation(@RequestBody AiUserRequireReqVo req) {
        AiUserRequireRelation requireRelation = new AiUserRequireRelation();
        requireRelation.setUserId(getUserId());
        requireRelation.setRequireId(req.getRequireId());
        requireRelation.setStatus(req.getStatus());
        requireRelation.setContent(req.getContent());
        int result = userRequireRelationService.insertAiUserRequireRelation(requireRelation);

        // 如果接受，则插入意向合作内容
        if (!req.getStatus().equalsIgnoreCase("1") || StrUtil.isNotBlank(req.getContent())) {
            AiRequirePlan aiRequirePlan = new AiRequirePlan();
            aiRequirePlan.setUserId(getUserId());
            aiRequirePlan.setRequireId(req.getRequireId());
            aiRequirePlan.setContent(req.getContent());
            requirePlanService.insertAiRequirePlan(aiRequirePlan);
        }
        return AjaxResult.success(result);
    }

    @GetMapping(value = "/list/relation")
    @ApiOperation(value = "获取当前用户的接受合作意向的公告商机信息列表(带分页参数)")
    public AjaxResult listRelation(@RequestParam(value = "current", required = false) Long current,
                                   @RequestParam(value = "size", required = false) Long size) {
        // 根据用户拒绝的商机标签，进行过滤，就不再推荐该关键词的商机
        AiUserRequireRelation requireRelation = new AiUserRequireRelation();
        requireRelation.setUserId(getUserId());
        requireRelation.setStatus("1"); // 查找用户拒绝的商机
        List<AiUserRequireRelation> list = userRequireRelationService.selectAiUserRequireRelationList(requireRelation);
        List<Long> requireIds = new ArrayList<>();
        String tags = null;
        if (CollUtil.isNotEmpty(list)) {
            requireIds = list.stream().map(AiUserRequireRelation::getRequireId).collect(Collectors.toList());
            AiRequire require = requireService.selectAiRequireById(requireIds.get(0));
            tags = require.getTags();
        }

        // 查询不包括拒绝的商机同类的商机列表
        AiRequire require = new AiRequire();
        require.setTags(tags);
        require.setStatus("0"); // 查找正常状态的商机列表
        require.setScopeType("0"); // 查找公开范围的商机列表
        Map<String, Object> params = new HashMap<>();
        params.put("requireIds", requireIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
        params.put("page", SqlUtil.getLimit(current, size));
        require.setParams(params);
        List<AiRequire> requireList = requireService.selectAiRequireRelationList(require);
        if (CollUtil.isEmpty(requireList)) return AjaxResult.success(new ArrayList<>());
        return AjaxResult.success(requireList.stream().map(this::changeItem).collect(Collectors.toList()));
    }

    public static void main(String[] args) {
        List<Long> requireIds = new ArrayList<>();
        System.out.println(requireIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }

    private AiRequireVo changeItem(AiRequire require) {
        AiRequireVo resp = new AiRequireVo();
        BeanUtil.copyProperties(require, resp);
        SysUser sysUser = sysUserService.selectUserById(require.getUserId());
        if (null != sysUser) {
            resp.setUser(new SysUserVo(sysUser.getUserId(), sysUser.getNickName(), sysUser.getAvatar()));
        }
        resp.setShareCount(RandomUtil.randomInt(10, 100));
        AiRequirePlan aiRequirePlan = new AiRequirePlan();
        aiRequirePlan.setRequireId(require.getId());
        List<AiRequirePlan> planList = requirePlanService.selectAiRequirePlanList(aiRequirePlan);
        resp.setPlanCount(CollUtil.isEmpty(planList) ? 0 : planList.size());
        resp.setViewCount(RandomUtil.randomInt(20, 200));
        resp.setCollectionCount(RandomUtil.randomInt(0, 10));
        return resp;
    }
}
